package com.lanhao.aot.carrierintegration.dhlpaket;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpStatus;

/**
 * 优化版本  下单 -> 打单
 * @author kunzhou3
 *
 */
public class NewDHLPaketUtil {
	private static final Logger LOG = LoggerFactory.getLogger(NewDHLPaketUtil.class);
	private static final String ORDER_URL = "https://api.dhl.com/dgff/ecom/legacy/shipping-label";
	private static final String API_KEY = "N5onZAGDycXt9vvij5gTJUmMWGzcqFMu";
	private static final String PickupAccountId = "5370617";
	private static final String SoldToAccountId = "521721";
	
//	private static final String ORDER_URL = "https://api-uat.dhl.com/dgff/ecom/legacy/shipping-label";
//	private static final String API_KEY = "o8vyU0VlmJZy5iEntDJVsQH3SFSPK7j2";
//	private static final String PickupAccountId = "HKCYL001";
//	private static final String SoldToAccountId = "HKCYL001";
	
	private static final String LABEL_MAKE_URL = "https://www.ecs-dconnector.com";
	private static final String OFFSET_ID = "+08:00";
	private static final String CARRIER = "DHL_Paket";
	private static final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss" + OFFSET_ID);
	
	
	public static void main(String[] args) {
		String shipmentId = "PLRDE06080308176420-ANHE";
//		labelOrder(shipmentId);
		
		makerLabelUrl(shipmentId);
	}

	public static void labelOrder(String shipmentId) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		
		String nowTime = LocalDateTime.now().format(fmt);
		JSONObject request = new JSONObject();
		JSONObject labelRequest = new JSONObject();
		JSONObject hdr = new JSONObject();
		
		hdr.put("messageType", "LABEL");
		hdr.put("messageDateTime", nowTime);
		hdr.put("messageVersion", "1.4");
		hdr.put("messageLanguage", "en");
		labelRequest.put("hdr", hdr);
		
		JSONObject bd = new JSONObject();
		
		bd.put("pickupAccountId", PickupAccountId);
		bd.put("soldToAccountId", SoldToAccountId);
		bd.put("pickupDateTime", nowTime);
		
		bd.put("consolidatedLabelRequired", "Y"); // TODO 新增
		
		JSONObject shipperAddress = new JSONObject();
		shipperAddress.put("companyName", null);
		shipperAddress.put("name", "Benjamin Linden");
		shipperAddress.put("address1", "Kurt-Schumacher-Str. 24");
//		shipperAddress.put("address2", "longcheng Building, No. 20 Bulong Road, Buji Stree");
//		shipperAddress.put("address3", "tFeng Dinglong");
		shipperAddress.put("city", "Hannover");
		shipperAddress.put("state", null);
//		shipperAddress.put("district", "Longgang District");
		shipperAddress.put("country", "DE");
//		shipperAddress.put("phone", "13590152579");
		shipperAddress.put("postCode", "30159");
//		shipperAddress.put("email", "2641454906@qq.com");
		bd.put("shipperAddress", shipperAddress);
		
		JSONArray shipmentItems = new JSONArray();
		JSONObject shipmentItem = new JSONObject();
		JSONObject consigneeAddress = new JSONObject();
		consigneeAddress.put("companyName", null);
		consigneeAddress.put("name", "HUITONG Int. COMPANY,DE-RTN-AE");
		consigneeAddress.put("address1", "Treseburger Str. 22A");
		consigneeAddress.put("address2", null);
		consigneeAddress.put("address3", null);
		consigneeAddress.put("city", "Berlin");
		consigneeAddress.put("state", "BL");
		consigneeAddress.put("district", null);
		consigneeAddress.put("country", "DE");
		consigneeAddress.put("phone", "0000000000");
		consigneeAddress.put("postCode", "13129");
//		consigneeAddress.put("email", "marco_zen@t-online.de");
		
		shipmentItem.put("consigneeAddress", consigneeAddress);
		shipmentItem.put("shipmentID", shipmentId);
		shipmentItem.put("deliveryConfirmationNo", null);
		shipmentItem.put("packageDesc", "ANHE SKU");
		shipmentItem.put("totalWeight", 300);
		shipmentItem.put("totalWeightUOM", "G");
		shipmentItem.put("dimensionUOM", "CM");
		shipmentItem.put("height", null);
		shipmentItem.put("length", null);
		shipmentItem.put("width", null);
		shipmentItem.put("customerReference1", null);
		shipmentItem.put("customerReference2", null);
		shipmentItem.put("productCode", "PLR");
		shipmentItem.put("incoterm", "DDP");
		shipmentItem.put("contentIndicator", null);
		shipmentItem.put("totalValue", 5.00);
		shipmentItem.put("currency", "USD");
		shipmentItem.put("remarks", null);
		
		JSONArray shipmentContents = new JSONArray();
		JSONObject shipmentContent = new JSONObject();
		shipmentContent.put("skuNumber", "ANHE SKU");
		shipmentContent.put("description", "ANHE SKU");
		shipmentContent.put("descriptionImport", null);
		shipmentContent.put("descriptionExport", "ANHE SKU");
		shipmentContent.put("itemValue", 5.00);
		shipmentContent.put("itemQuantity", 1);
		shipmentContent.put("grossWeight", null);
		shipmentContent.put("netWeight", null);
		shipmentContent.put("weightUOM", "G");
//		shipmentContent.put("contentIndicator", null);
		shipmentContent.put("countryOfOrigin", "CN");
		shipmentContent.put("hsCode", null);
		shipmentContents.add(shipmentContent);
		
		shipmentItem.put("shipmentContents", shipmentContents);
		
		shipmentItems.add(shipmentItem);
		bd.put("shipmentItems", shipmentItems);
		
		JSONObject label = new JSONObject();
		label.put("pageSize", "400x600");
		label.put("format", "pdf");
		label.put("layout", "1x1");
		bd.put("label", label);
		
		labelRequest.put("bd", bd);
		
		request.put("labelRequest", labelRequest);
		
		Map<String, String> headers = Maps.newConcurrentMap();
		headers.put("DHL-API-Key", API_KEY);
		headers.put("Content-Type", "application/json");
		String respBody = HttpRequest.post(ORDER_URL).addHeaders(headers).body(request.toJSONString()).timeout(10000).execute().body();
		stopWatch.stop();
		long totalTimeMillis = stopWatch.getTotalTimeMillis();
		LOG.info("请求label接口返回结果 url={}, request={}, result={}，耗时={}ms", ORDER_URL, labelRequest.toJSONString(), respBody, totalTimeMillis);
		
		if(StringUtils.isNotBlank(respBody)) {
			JSONObject respObject = JSON.parseObject(respBody);
			Integer status = respObject.getInteger("status");
			if(status != null) {
				String title = respObject.getString("title");
				String details = respObject.getString("details");
				LOG.info("请求面单失败了，失败原因e={}", title + ":" + details);
			} else {
				JSONObject labelResponse = respObject.getJSONObject("labelResponse");
				if(labelResponse == null) {
					return;
				}
				JSONObject bdObject = labelResponse.getJSONObject("bd");
				JSONArray labelsArray = bdObject.getJSONArray("labels");
				if(labelsArray != null) {
					JSONObject labelObject = labelsArray.getJSONObject(0);
					JSONObject labelResponseStatus = labelObject.getJSONObject("responseStatus");
					Integer labelStatusCode = labelResponseStatus.getInteger("code");
					if(labelStatusCode == HttpStatus.HTTP_OK) {
						LOG.info("获取面单下单成功，shipmentId={}", shipmentId);
					} else {
						String labelMessage = labelResponseStatus.getString("message");
						JSONArray labelMessageDetails = labelResponseStatus.getJSONArray("messageDetails");
						JSONObject labelDetailObject = labelMessageDetails.getJSONObject(0);
						String labelMessageDetail = labelDetailObject.getString("messageDetail");
						LOG.info("请求面单失败了，失败原因：message={}, detail={}", labelMessage, labelMessageDetail);
					}
				} else {
					JSONObject responseStatus = bdObject.getJSONObject("responseStatus");
					String message = responseStatus.getString("message");
					JSONArray messageDetails = responseStatus.getJSONArray("messageDetails");
					JSONObject detailObject = messageDetails.getJSONObject(0);
					String messageDetail = detailObject.getString("messageDetail");
					LOG.info("请求面单失败了，失败原因:message={}, detail={}", message, messageDetail);
				}
			}
			
		}
	}
	
	public static void makerLabelUrl(String cnn) {
		try {
			final String API_URL = LABEL_MAKE_URL + "/open/api";
	//		public static final String API_URL = "https://dhlecs-dconnectsys.com/open/api";
	//		final String App_Key = "c85370db06c575ebd5f69550ea6f8a887aea9597";
	//		final String App_Secret = "3624b2fa2a133b142d44158dc6b73e2b1266b763";
			
			final String PROD_App_Key = "10aee1e0940f5378c9627adac9831368d905e67a";
			final String PROD_App_Secret = "22449418b5e8a4166b261500a1796732c6ab2104";
			
			final String Make_Label_API = "makerPLRLabel";
			
			StopWatch stopWatch = new StopWatch();
			stopWatch.start();
			Map<String, Object> paramMap = new HashMap<>();
			long currentTimeMillis = System.currentTimeMillis();
			paramMap.put("api_name", Make_Label_API);
			paramMap.put("app_key", PROD_App_Key);
			JSONObject param = new JSONObject();
//			param.put("status", "1"); // 1:更新包裹重量并获取面单URL
			param.put("ccn", cnn);
//			param.put("weight", 250); // 单位g
			String paramString = param.toString();
			
			paramMap.put("param_json", paramString);
			paramMap.put("timestamp", currentTimeMillis);
			
			String sign = "api_name=" + Make_Label_API + "&app_key=" + PROD_App_Key + "&app_secret=" + PROD_App_Secret
					+ "&param_json=" + paramString + "&timestamp=" + currentTimeMillis;
			sign = DigestUtils.sha1Hex(sign);
			paramMap.put("sign", sign);
			
			LOG.info("签名传sign={}, 请求参数paramMap={}", sign, paramMap);
			String body = HttpRequest.post(API_URL).form(paramMap).timeout(5000).execute().body();
			stopWatch.stop();
			long totalTimeMillis = stopWatch.getTotalTimeMillis();
			LOG.info("请求D-Connect返回结果 url={}, result={}，耗时={}ms", API_URL, body, totalTimeMillis);
			FileUtils.write(new File("D:/label_resp.txt"), body, "UTF-8");
			if (StringUtils.isNotBlank(body)) {
				JSONObject resultObject = JSON.parseObject(body);
				Boolean success = resultObject.getBoolean("success");
				if (success != null && success) {
					JSONObject t = resultObject.getJSONObject("result");
					String mailNo = t.getString("dspTrackingNumber");
					String labelUrl = t.getString("labelUrl");
					LOG.info("响应成功：mailNo={}, labelUrl={}", mailNo, labelUrl);
				} else {
					Integer code = resultObject.getInteger("code");
					String message = resultObject.getString("message");
					LOG.info("响应失败：code={}, message={}", code, message);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
